package com.daxia.ogmall.web.controller;

import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daxia.ogmall.common.AuditStatus;
import com.daxia.ogmall.common.CompanyStatus;
import com.daxia.ogmall.common.FactoryInfoStatus;
import com.daxia.ogmall.common.Logs;
import com.daxia.ogmall.common.SmsSendType;
import com.daxia.ogmall.common.UserType;
import com.daxia.ogmall.dto.CityDTO;
import com.daxia.ogmall.dto.CompanyDTO;
import com.daxia.ogmall.dto.DesignerDTO;
import com.daxia.ogmall.dto.DistrictDTO;
import com.daxia.ogmall.dto.FactoryInfoDTO;
import com.daxia.ogmall.dto.UserDTO;
import com.daxia.ogmall.model.City;
import com.daxia.ogmall.model.Province;
import com.daxia.ogmall.util.DevUtils;
import com.daxia.ogmall.util.SmsService;
import com.daxia.ogmall.util.StringUtil;
import com.daxia.ogmall.util.ValidationUtils;
import com.google.code.kaptcha.impl.DefaultKaptcha;

@Controller
@RequestMapping("user")
public class UserController extends BaseController {
	private static Logger logger = Logger.getLogger(UserController.class);
	private String errorMsg;

    @RequestMapping(value = "/login")
    public String login(Map<String, Object> map,HttpServletRequest request) {
    	map.put("username", "kevin");
    	String error = request.getParameter("error");
    	if(error != null) {
    		map.put("errorMsg", "对不起，该用户不存在或用户没有经过平台认证，请确认或重新注册登录，谢谢!");
    	}
    	map.put("isLocal", DevUtils.isLocal());
        return "user/user_login";
    }
    
    @RequestMapping(value = "/doLogin")
    public String doLogin(String username, String password, Map<String, Object> map,HttpServletRequest request) {
     	UserDTO user = userService.login(username, password);
     	if (user == null) {
     		map.put("msg", "用户名不存在，或用户名密码错误!");
     		return "user/user_login";
     	} else {
     		return "redirect:/index";
     	}
    }

    @RequestMapping(value = "/register")
    public String register(String registerType,Map<String, Object> map) {    //注册中转页面
    	map.put("provinces", provinceService.findAll());    //查出所有省份
		map.put("houseStyles", houseStyleService.findAll());
    	if("designer".equals(registerType)) {
    		return "user/user_designerRegisterStepO";
    	} else if("mini".equals(registerType)) {
    		return "user/mini/user_companyMiniStepO";
    	} else if("factory".equals(registerType)) {
    		return "user/user_factoryRegister";
    	} else {
    		//return "user/user_companyRegisterStepO";
    		return "user/mini/user_companyMiniStepO";
    	}
    }
    
    @ResponseBody
    @RequestMapping(value = "/findPwd")
    public String findPwd(String mobile,String password,String passwordConfirm,String valiCode) {
    	if (logger.isDebugEnabled()) {
			logger.debug("findPwd, mobile: " + mobile + ", password: " + password + ", passwordConfirm: " + passwordConfirm + ", valiCode: " + valiCode);
		}
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(mobile), "请填写手机号码!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(password), "请填写密码!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(passwordConfirm), "请填写确认密码!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(valiCode), "请填写短信验证码!");
    	ValidationUtils.assertTrue(password.equals(passwordConfirm), "密码与确认密码不一致!");
    	UserDTO queryUser = new UserDTO();
    	queryUser.setMobile(mobile);
    	UserDTO userDto = userService.findOne(queryUser);
    	ValidationUtils.assertTrue(userDto != null, "该手机号码未被注册，请确认手机号码是否正确!");
    	userDto.setPassword(passwordEncoder.encodePassword(password, userDto.getUsername()));
    	if (logger.isDebugEnabled()) {
			logger.debug("encoded password: " + userDto.getPassword() + ", mobile: " + mobile);
		}
    	userService.updateAllFields(userDto);
    	return okJson();
    }
    
    @ResponseBody
    @RequestMapping(value = "/getSmsValiCode")
    public String getSmsValiCode(String mobile,HttpServletRequest request, HttpServletResponse response) throws Exception {   //获取短信验证码
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(mobile), "请填写手机号码!");
    	//获取验证码
		DefaultKaptcha captchaProducer = new DefaultKaptcha();
	    captchaProducer.setConfig(new com.google.code.kaptcha.util.Config(new Properties()));
	    String capText = captchaProducer.createText();
    	Map<String,Object> contentMap = new Hashtable<String, Object>();
    	contentMap.put("code", capText);
    	SmsService.sendWithTemplate(mobile, SmsSendType.CommonValidation.getValue(), contentMap);;
    	request.getSession().setAttribute("smsValiCode", capText);
    	return okJson();
    }
    
    @ResponseBody
    @RequestMapping(value="/doFactoryReg")
    public String doFactoryReg(String registerType,UserDTO userDto,FactoryInfoDTO factory,Map<String, Object> map) {
    	ValidationUtils.assertTrue(userDto != null, "请填写用户信息!");
    	ValidationUtils.assertTrue(factory != null, "请填写工厂信息!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(userDto.getMobile()), "请填写手机号码!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(userDto.getRealName()), "请填写联系人姓名!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(factory.getCompanyName()), "请填写公司名称!");
    	ValidationUtils.assertTrue(userDto.getProvince() != null, "请选择工厂所在省份!");
    	ValidationUtils.assertTrue(userDto.getCity() != null, "请选择工厂所在市区!");
    	ValidationUtils.assertTrue(userDto.getDistrict() != null, "请选择工厂所在区域!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(factory.getCompanySize()), "请选择公司规模!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(userDto.getMobile()), "请填写联系人电话!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(factory.getImages()), "请上传产品图片!");
    	userDto.setUsername(factory.getCompanyName());
    	Long userId = null;
    	Date date = new java.util.Date();
		userDto.setPassword(passwordEncoder.encodePassword(userDto.getPassword(), userDto.getUsername()));
		userDto.setType(UserType.Factory.getValue());
		userDto.setCreatetime(date);
		userId = userService.create(userDto);
		userDto.setId(userId);
		factory.setUser(userDto);
		factory.setStatus(FactoryInfoStatus.Add.getValue());
		factoryInfoService.create(factory);
		return createOkWithUser(userId);
    }
    
    @ResponseBody
    @RequestMapping(value = "/doCompanyMiniReg")
    public String doCompanyMiniReg(String registerType,String passwordConfirm,String valicode,String recUserName,
    		UserDTO userDto,CompanyDTO company,Map<String, Object> map,HttpServletRequest request, HttpServletResponse response) {   //装修公司快速注册
    	ValidationUtils.assertTrue(userDto != null, "请填写用户信息!");
    	userDto.setUsername(userDto.getMobile());
    	//ValidationUtils.assertTrue(StringUtils.isNotBlank(userDto.getUsername()), "请填写登录用户名!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(userDto.getMobile()), "请填写手机号码!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(userDto.getRealName()), "请填写联系人姓名!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(company.getName()), "请填写公司名称!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(valicode), "请填写验证码信息!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(userDto.getPassword()), "请填写密码!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(passwordConfirm), "请填写确认密码!");
    	ValidationUtils.assertTrue(userDto.getPassword().equals(passwordConfirm), "确认密码不正确!");
    	ValidationUtils.assertTrue(userDto.getProvince() != null, "请选择省份!");
    	ValidationUtils.assertTrue(userDto.getProvince() != null, "请选择城市!");
    	ValidationUtils.assertTrue(userDto.getProvince() != null, "请选择地区!");
    	//String smsValiCode = (String) request.getSession().getAttribute("smsValiCode");
    	//ValidationUtils.assertTrue(valicode.equals(smsValiCode), "手机验证码错误!");
    	//userDto.setUsername(userDto.getMobile());       //快速注册，以手机号码为用户名
    	userDto.setPassword(passwordEncoder.encodePassword(userDto.getPassword(), userDto.getUsername()));   //密码加密
    	//查看用户是否已经注册
    	UserDTO findUser = new UserDTO();
    	findUser.setUsername(userDto.getUsername());  
    	findUser = userService.findOne(findUser);
    	Long userId = null;
    	if(StringUtils.isNotBlank(recUserName)) { //推荐人
    		//recUserName = recUserName.substring(1);
    		UserDTO recUser = new UserDTO();
    		recUser.setUsername(recUserName);
    		recUser = userService.findOne(recUser);
    		if(recUser == null) {
    			return createFailureInfo("推荐用户没有找到!");
    		} else {
    			userDto.setRecUser(recUser);
    		}
    	}
    	if(findUser != null) {
    		return createFailureInfo("用户已经注册，请重新填写!");
    	} else {
    		Date date = new java.util.Date();
			userDto.setType(UserType.DecorateCompany.getValue());
			userDto.setCreatetime(date);
			userId = userService.create(userDto);
			userDto.setId(userId);
			company.setUser(userDto);
			company.setStatus(CompanyStatus.Add.getValue());
			companyService.create(company);
    	}
    	request.getSession().setAttribute("registerUserId", userId);
    	request.getSession().setAttribute("registerUser", userDto);
    	return createOkWithUser(userId);
    }
    
    @ResponseBody
    @RequestMapping(value = "/doCompanyRegister")
    public String doCompanyRegister(String registerType,String passwordConfirm,String valiCode,
    		UserDTO userDto,FactoryInfoDTO factoryDto,Map<String, Object> map,HttpServletRequest request, HttpServletResponse response) {
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(userDto.getUsername()), "用户名不能为空!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(valiCode), "验证码不能为空!");
    	String sessionCode = (String)request.getSession().getAttribute("validateCode");
    	ValidationUtils.assertTrue(valiCode.equals(sessionCode), "验证码输入错误!");
    	if(checkUser(userDto) && checkFactory(factoryDto)) {   //校验数据
    		String userName = userDto.getUsername(); 
        	if(!passwordConfirm.equals(userDto.getPassword())) {
        		return createFailureInfo("两次密码输入不一致，请重新对照输入!");
        	}
        	UserDTO findUser = new UserDTO();
        	findUser.setUsername(userName);
        	findUser = userService.findOne(findUser);
        	Long userId = null;
        	if(findUser != null) {
        		return createFailureInfo("用户已经注册，请重新填写!");
        	} else {
        		Date date = new java.util.Date();
    			userDto.setPassword(passwordEncoder.encodePassword(userDto.getPassword(), userDto.getUsername()));
    			userDto.setType(UserType.DecorateCompany.getValue());
    			userDto.setCreatetime(date);
    			userId = userService.create(userDto);
    			userDto.setId(userId);
        		if(factoryDto != null ) {
        			factoryDto.setUser(userDto);
        			factoryDto.setCreateTime(date);
        			factoryInfoService.create(factoryDto);
        		} else {
        			return createFailureInfo("对不起，请完善工厂信息!");
        		}
        	}
        	request.getSession().setAttribute("registerUserId", userId);
        	request.getSession().setAttribute("registerUser", userDto);
        	return createOkWithUser(userId);
    	} else {
    		return createFailureInfo(errorMsg);
    	}
    }
    
    @ResponseBody
    @RequestMapping(value = "/doDesignerRegister")
    public String doDesignerRegister(String registerType,String passwordConfirm,String valiCode,UserDTO userDto,String recUserName,
    		DesignerDTO designer,Map<String, Object> map,HttpServletRequest request, HttpServletResponse response) {
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(userDto.getUsername()), "手机号不能为空!");
    	ValidationUtils.assertTrue(StringUtil.isChinaPhoneLegal(userDto.getUsername()), "手机号格式错误!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(userDto.getRealName()), "昵称不能为空!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(valiCode), "验证码不能为空!");
    	String sessionCode = (String)request.getSession().getAttribute("validateCode");
    	ValidationUtils.assertTrue(valiCode.equals(sessionCode), "验证码输入错误!");
//    	ValidationUtils.assertTrue(StringUtils.isNotBlank(designer.getCompany()), "公司名称不能为空!");
    	ValidationUtils.assertTrue(designer.getCompanyUser()!= null&&designer.getCompanyUser().getId()!= null, "装修公司不能为空!");
//    	ValidationUtils.assertTrue(StringUtils.isNotBlank(designer.getDesignImages()), "请上传作品图片!");
    	ValidationUtils.assertTrue(StringUtils.isNotBlank(designer.getGoodAtStyles()), "请选择擅长的风格!");
    	ValidationUtils.assertTrue(designer.getWorkAge() != null, "请填写从业年限!");
//    	ValidationUtils.assertTrue(StringUtils.isNotBlank(designer.getRegisterAddress()), "公司注册地址不能为空!");
//    	ValidationUtils.assertTrue(StringUtils.isNotBlank(designer.getWorkPlace()), "公司办公地址不能为空!");
//    	designer.setTopDesignerImage(designer.getDesignImages().split(",")[0]);
    	userDto.setMobile(userDto.getUsername());
    	if(checkUser(userDto)) {
    		String userName = userDto.getUsername(); 
        	if(!passwordConfirm.equals(userDto.getPassword())) {
        		return createFailureInfo("两次密码输入不一致，请重新对照输入!");
        	}
        	UserDTO findUser = new UserDTO();
        	findUser.setUsername(userName);
        	findUser = userService.findOne(findUser);
        	Long userId = null;
        	if(StringUtils.isNotBlank(recUserName)) { //推荐人
        		UserDTO recUser = new UserDTO();
        		recUserName = recUserName.substring(1);
        		recUser.setUsername(recUserName);
        		recUser = userService.findOne(recUser);
        		if(recUser == null) {
        			return createFailureInfo("推荐用户没有找到!");
        		} else {
        			userDto.setRecUser(recUser);
        		}
        	}
        	if(findUser != null) {
        		return createFailureInfo("用户已经注册，请重新填写!");
        	} else {
        		Date date = new java.util.Date();
    			userDto.setPassword(passwordEncoder.encodePassword(userDto.getPassword(), userDto.getUsername()));
    			userDto.setType(UserType.Designer.getValue());
    			userDto.setCreatetime(date);
    			userId = userService.create(userDto);
    			userDto.setId(userId);
        		if(designer != null ) {
        			CompanyDTO c = companyService.load(designer.getCompanyUser().getId());
        			designer.setCompany(c.getName());
        			designer.setUser(userDto);
        			designer.setAuditStatus(AuditStatus.NotAudit.getValue());
        			designerService.create(designer);
        		} else {
        			return createFailureInfo("对不起，请完善设计师信息!");
        		}
        	}
        	request.getSession().setAttribute("registerUserId", userId);
        	request.getSession().setAttribute("registerUser", userDto);
        	return createOkWithUser(userId);
    	} else {
    		return createFailureInfo(errorMsg);
    	}
    }
    
    public String createOkWithUser(Long userId) {    //创建一个带着注册用户的成功json
    	JSONObject jObj = new JSONObject();
    	jObj.put("success", true);
    	jObj.put("userId", userId);
    	return jObj.toJSONString();
    }
    
    @RequestMapping("goNextStep")
    public String goNextStep(String registerType,String step,Map<String, Object> map,HttpServletRequest request, HttpServletResponse response) {   //跳转到下一个页面，根据注册类型和步骤跳转\
    	Long userId = (Long) request.getSession().getAttribute("registerUserId");
    	map.put("userId", userId);
    	map.put("user", request.getSession().getAttribute("registerUser"));
    	if("factory".equals(registerType)) {   //工厂注册
    		UserDTO user = new UserDTO();
    		user.setId(userId);
    		FactoryInfoDTO factory = new FactoryInfoDTO();
    		factory.setUser(user);
    		factory = factoryInfoService.findFactoryByUserId(userId);
    		map.put("factory", factory);
    		
    		if("2".equals(step)) {
    			return "user/user_companyRegisterStepT";
    		} else if("3".equals(step)){
    			return "user/user_companyRegisterStepTh";
    		}
    	} else if("designer".equals(registerType)) {
    		if("2".equals(step)) {
    			return "user/user_designerRegisterStepT";
    		}
    	} else if("mini".equals(registerType)) {
    		UserDTO user = new UserDTO();
    		user.setId(userId);
    		CompanyDTO company = new CompanyDTO();
    		company.setUser(user);
    		company = companyService.findCompanyByUserId(userId);
    		map.put("company", company);
    		
    		if("2".equals(step)) {
    			return "user/mini/user_companyMiniStepT";
    		} else if("3".equals(step)){
    			return "user/mini/user_companyMiniStepTh";
    		}
    	}
    	return null;
    }
    
    @ResponseBody
    public String createFailureInfo(String msg) {   //返回错误信息
    	JSONObject json = new JSONObject();
    	json.put("success", false);
    	json.put("msg", msg);
    	return json.toJSONString();
    }
    
    public boolean checkFactory(FactoryInfoDTO factoryInfo) {   //检验工厂信息是否完备
    	if(isStrNullOrBlanck(factoryInfo.getEmail())) {
    		errorMsg = "邮箱不能为空!";
    		return false;
    	}
    	if(isStrNullOrBlanck(factoryInfo.getCompanyName())) {
    		errorMsg = "公司名称不能为空!";
    		return false;
    	}
    	/*if(isStrNullOrBlanck(factoryInfo.getLegalPerson())) {
    		errorMsg = "公司法人不能为空!";
    		return false;
    	}*/
    	
    	if(isStrNullOrBlanck(factoryInfo.getOfficeAddress())) {
    		errorMsg = "办公地址不能为空!";
    		return false;
    	}
    	if(isStrNullOrBlanck(factoryInfo.getRegisterAddress())) {
    		errorMsg = "公司注册地址不能为空!";
    		return false;
    	}
    	if(isStrNullOrBlanck(factoryInfo.getImages())) {
    		errorMsg = "公司证件照片不能为空!";
    		return false;
    	}
    	return true;
    }
    
    @ResponseBody
    @RequestMapping(value = "checkMobile")
    public String checkMobile(String mobile) {
    	UserDTO user = userService.findByUsername(mobile);
    	if (user == null) {
    		return ok();
    	} else {
    		throw new RuntimeException("该手机号码已经注册了");
    	}
    }
    
    public boolean checkUser(UserDTO userInfo) {  //检验用户各参数是否完备
    	if(isStrNullOrBlanck(userInfo.getUsername())) {
    		errorMsg = "用户名不能为空!";
    		return false;
    	}
    	if(isStrNullOrBlanck(userInfo.getPassword())) {
    		errorMsg = "用户密码不能为空!";
    		return false;
    	}
    	if(isStrNullOrBlanck(userInfo.getMobile())) {
    		errorMsg = "用户手机号码不能为空!";
    		return false;
    	}
    	if(userInfo.getProvince() == null||userInfo.getProvince().getId()==null) {
    		errorMsg = "所在省份不能为空!";
    		return false;
    	}
    	if(userInfo.getCity() == null||userInfo.getCity().getId()==null) {
    		errorMsg = "所在市区不能为空!";
    		return false;
    	}
    	if(userInfo.getDistrict() == null||userInfo.getDistrict().getId()==null) {
    		errorMsg = "所在地区不能为空!";
    		return false;
    	}
    	return true;
    }
    
    public boolean isStrNullOrBlanck(String str) {
    	return str == null || "".equals(str.trim());
    }
    
    @ResponseBody
    @RequestMapping("findArea")
    public String findArea(Long provinceId, Long cityId) throws Exception {
        if (cityId != null) {
            DistrictDTO query = new DistrictDTO();
            query.setCity(new City());
            query.getCity().setId(cityId);
            List<DistrictDTO> districts = districtService.find(query, null);
            JSONArray array = new JSONArray();
            for (DistrictDTO d : districts) {
                JSONObject json = new JSONObject();
                json.put("id", d.getId());
                json.put("name", d.getName());
                array.add(json);
            }
            return array.toJSONString();
        } else if (provinceId != null) {
            CityDTO query = new CityDTO();
            query.setProvince(new Province());
            query.getProvince().setId(provinceId);
            List<CityDTO> cities = cityService.find(query, null);
            JSONArray array = new JSONArray();
            for (CityDTO d : cities) {
                JSONObject json = new JSONObject();
                json.put("id", d.getId());
                json.put("name", d.getName());
                array.add(json);
            }
            return array.toJSONString();
        }
        return null;
    }

    @ResponseBody
	@RequestMapping("convertMobile")
	public String convertMobile(String mobile, HttpServletRequest request) throws Exception {
    	Logs.COMMON.debug("mobile: " + mobile);
    	String username = mobile;
    	UserDTO user = userService.findByMobile(mobile);
    	if (user != null) {
    		username = user.getUsername();
    	}
    	JSONObject json = new JSONObject();
    	json.put("success", true);
    	json.put("username", username);
    	Logs.COMMON.debug(json);
    	request.getSession().setAttribute("loginUsername", mobile);
		return json.toJSONString();
	}
    
}	
